﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThreeByte.TaskModel;
using ThreeByte.ActiveDeck.Config;
using log4net;
using System.Windows.Threading;
using System.ComponentModel;
using ThreeByte.ActiveDeck.Service;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using ThreeByte.ActiveDeck.Controls;

namespace ThreeByte.ActiveDeck.AddIn.Config {
    class GetWebConfigTask : AsyncTaskBase {

        private static readonly ILog log = LogManager.GetLogger(typeof(GetWebConfigTask));
        private static readonly XNamespace ns = ServiceConfiguration.NAMESPACE;

        private CoreConfig Config;
        public Dictionary<int, ObservableCollection<GroupUser>> UserCollectionDict;
        public Version availableVersion;
        
        public GetWebConfigTask(CoreConfig config) {
            Config = config;
            UserCollectionDict = new Dictionary<int, ObservableCollection<GroupUser>>();
        }

        protected override void Run(BackgroundWorker bw, DoWorkEventArgs e) {
            if(bw.CancellationPending) {
                e.Cancel = true;
                return;
            }

            // retrieve add-in version
            availableVersion = WebServiceClient.GetAddInVersion();
            if(availableVersion == null) {
                log.Warn("Cannot retrieve available AddIn version");
            } 

            // Get Presentation Group Users
            WebServiceClient client = new WebServiceClient(Config.PresenterLogin);
            foreach(PresentationGroup pg in Config.PresentationGroups) {
                XElement groupUsers = client.GetGroupUsers(Config.ID, pg.ID);
                ObservableCollection<GroupUser> users = new ObservableCollection<GroupUser>();
                foreach(XElement user in groupUsers.Elements(ns + "User")) {
                    users.Add(new GroupUser(user.Attribute("UserName").Value));
                }
                UserCollectionDict.Add(pg.ID, users);
            }
        }        
    }
}
